import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
let scene, camera, renderer, controls

/* 
  uniform变量
*/
function init() {
  scene = new THREE.Scene()
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  camera.position.set(0, 0, 5)
  renderer = new THREE.WebGLRenderer({ antialias: true })
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)

  controls = new OrbitControls(camera, renderer.domElement)
  controls.enableDamping = true

  const axesHelper = new THREE.AxesHelper(5)
  scene.add(axesHelper)
};

function createBasic () {
  // 1. 创建平面
  const geometry = new THREE.PlaneGeometry(1, 1)
  // 自己自定义属性position2，然后赋值为geometry.attributes.position
  geometry.setAttribute('position2', geometry.attributes.position)
  
  // 2. 创建材质
  const material = new THREE.ShaderMaterial({
    // ShaderMaterial材质中传入`uniforms`变量，里面写自定义变量
    // 顶点着色器和片元着色器都可以使用
    // 着色器uniform声明
    // 顶点着色器中使用
    vertexShader: `
      attribute vec3 position2;
      uniform float posX;
      void main () {
        vec4 v = vec4(position2, 1.0);
        v.x += posX;
        gl_Position = projectionMatrix * viewMatrix * modelMatrix * v;
      }
    `,
    // 片元着色器
    fragmentShader: `
      void main () {
        gl_FragColor = vec4(0, 1.0, 0, 0.9);
      }
    `,
    uniforms: {
      posX: {
        value: 2.0 // 初始值位移x轴2.0个单位
      }
    }
  })
  // 3. 创建物体
  const mesh = new THREE.Mesh(geometry, material)
  scene.add(mesh)
}

function renderLoop() {
  renderer.render(scene, camera)
  controls.update()
  requestAnimationFrame(renderLoop)
}

init()
createBasic()
renderLoop() 

